package com.qining618.cms.cms.service.impl;

import com.qining618.cms.cms.domain.Comment;
import com.qining618.cms.cms.mapper.CommentMapper;
import com.qining618.cms.cms.mapper.ContentCountMapper;
import com.qining618.cms.cms.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qining618.cms.cms.service.ContentCountService;
import com.qining618.cms.cms.service.SensitivityService;
import com.qining618.cms.ucenter.mapper.UserMapper;
import com.qining618.cms.ucenter.service.UserService;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * CMS评论表 服务实现类
 * </p>
 *
 * @author qining
 * @date 2019-09-17
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserService userService;
    @Autowired
    private ContentCountService contentCountService;
    @Autowired
    private SensitivityService sensitivityService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Comment save(Long userId, Long contentId, String text, String ip, Long parentId) {
        Comment comment = new Comment();

        if (parentId != null && parentId != 0) {
            boolean isExist = this.baseMapper.existById(parentId);
            if (isExist) {
                comment.setParentId(parentId);
            }
        }
        // 敏感词过滤
        comment.setText(sensitivityService.replaceSensitivity(text));
        comment.setCommentUserId(userId);
        comment.setContentId(contentId);
        comment.setText(text);
        comment.setIp(ip);
        comment.init();

        // 累计今日留言数
        this.userService.incTodayCommentTotal(userId);
        // 累计内容评论数
        this.contentCountService.incCommentCount(contentId);

        // 保存评论信息
        this.baseMapper.insert(comment);

        return comment;
    }
}
